package com.demo1216;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.WritableByteChannel;
import java.util.List;
import java.util.UUID;

@MultipartConfig(location = "F:\\train\\demo\\javaweb2112\\1209\\web\\upload", fileSizeThreshold = 1024 * 1024, maxFileSize = 1024 * 1024 * 5, maxRequestSize = 1024 * 1024 * 5 * 5)
@WebServlet("/upload.do")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getParameter("UTF-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        Part part = req.getPart("file");
        //获取文件后缀名，即文件类型
        String realFileName = part.getSubmittedFileName();
        String type = realFileName.substring(realFileName.lastIndexOf("."));
        //通过UUID 生成随机文件名
        String fileName = UUID.randomUUID().toString() + type;
        //获取项目下的该文件夹路径，必须先创建文件夹
        String path = "F:\\train\\demo\\javaweb2112\\1209\\web\\upload\\" + fileName;
        part.write(path);
        //将文件名信息回传至前端
        writer.write(fileName);
    }
}
